package com.itheima.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.PageResult;
import com.itheima.common.ResultData;
import com.itheima.domain.UmsAdmin;
import com.itheima.domain.UmsAdminRoleRelation;
import com.itheima.domain.UmsRole;
import com.itheima.dto.AdminPasswordDto;
import com.itheima.interceptor.UserHolder;
import com.itheima.service.UmsAdminRoleRelationService;
import com.itheima.service.UmsAdminService;
import com.itheima.service.UmsResourceService;
import com.itheima.service.UmsRoleService;
import com.itheima.util.BCryptUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Component
public class AdminManager {

    @DubboReference
    private UmsAdminService umsAdminService;

    @DubboReference
    private UmsAdminRoleRelationService umsAdminRoleRelationService;

    @DubboReference
    private UmsResourceService umsResourceService;

    @DubboReference
    private UmsRoleService umsRoleService;

    // 根据用户名或姓名分页获取用户列表
    public ResultData getAdminByPage(Integer pageNum, Integer pageSize, String keyword) {
        Page<UmsAdmin> listPage = umsAdminService.getAdminByPage(pageNum, pageSize, keyword);
        return ResultData.ok(new PageResult(pageNum,pageSize, listPage.getTotal(), listPage.getPages(), listPage.getRecords()),"");
    }


    // 删除指定用户信息
    public ResultData delete(Integer id) {
        umsAdminService.remove(id);
        return ResultData.ok("","删除成功");
    }

    // 用户退出
    public ResultData logOut() {
        return ResultData.ok("","退出成功");
    }

    // 获取指定用户角色
    public ResultData getRolesInfo(Long adminId) {
        //根据 adminId 查询 roleId
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationService.getByAdminId(adminId);
        List<Long> roleIds = CollUtil.getFieldValues(umsAdminRoleRelations, "roleId", Long.class);
//        if(CollUtil.isEmpty(roleIds)){
//            return new ArrayList<>();
//        }
        // 查询角色信息
        List<UmsRole> umsRoles = umsRoleService.getByIds(roleIds);
        return ResultData.ok(umsRoles,"");

    }

    // 修改指定用户信息
    public ResultData update(UmsAdmin umsAdmin) {
        // 用户名为空,结束,返回错误信息
        if(StringUtils.isEmpty(umsAdmin.getUsername())){
            return ResultData.error("用户名不能为空!");
        }
        // 密码为空,结束,返回错误信息
        if(StringUtils.isEmpty(umsAdmin.getPassword())){
            return ResultData.error( "密码不能为空!");
        }
        // 校验邮箱格式,如果格式错误,返回错误信息
        if(StringUtils.isNotEmpty(umsAdmin.getEmail())){
            String check = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";
            if(!Pattern.matches(check, umsAdmin.getEmail())){
                return ResultData.error( "邮箱格式不正确!");
            }
        }
        umsAdminService.update(umsAdmin);
        return ResultData.ok("","修改成功");
    }

    // 修改账户状态
    public ResultData updateStatus(Integer id, Integer status) {
        umsAdminService.updateStatusById(id, status);
        return ResultData.ok(id,"修改成功");
    }


    // 给用户角色分配
    public ResultData updateAdminRole(Long adminId, List<Long> roleIds) {
        // 根据 adminId 查询 当前用户的 roleIds
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationService.getByAdminId(adminId);
        // 若存在
        if(CollUtil.isNotEmpty(umsAdminRoleRelations)){
            // 首先根据adminId删除原来的roleIds
            umsAdminRoleRelationService.removeByAdminId(adminId);
        }
        // 再批量添加新的 roleIds
        for (Long roleId : roleIds) {
            UmsAdminRoleRelation umsAdminRoleRelation = new UmsAdminRoleRelation();
            umsAdminRoleRelation.setAdminId(adminId);
            umsAdminRoleRelation.setRoleId(roleId);
            umsAdminRoleRelationService.save(umsAdminRoleRelation);
        }
        return ResultData.ok(roleIds.size(),"操作成功!");
    }

    // 用户注册
    public ResultData register(UmsAdmin umsAdmin) {
        // 用户名为空,结束,返回错误信息
        if(StringUtils.isEmpty(umsAdmin.getUsername())){
            return ResultData.error("用户名不能为空!");
        }
        // 密码为空,结束,返回错误信息
        if(StringUtils.isEmpty(umsAdmin.getPassword())){
            return ResultData.error( "密码不能为空!");
        }
        // 校验邮箱格式,如果格式错误,返回错误信息
        if(StringUtils.isNotEmpty(umsAdmin.getEmail())){
            String check = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";
            if(!Pattern.matches(check, umsAdmin.getEmail())){
                return ResultData.error( "邮箱格式不正确!");
            }
        }
        // 判断 username 是否存在,若存在, 则返回错误信息
        UmsAdmin admin = umsAdminService.findUserByName(umsAdmin.getUsername());
        if(ObjectUtil.isNotEmpty(admin)){
            return ResultData.error( "操作失败!");
        }

        //走到这一步, 则可以进行注册
        // 保存数据
       // umsAdmin.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        umsAdmin.setPassword(BCryptUtil.getPassword(umsAdmin.getPassword()));
        umsAdminService.save(umsAdmin);
        // 查询最新保存的数据
        UmsAdmin adminNew = umsAdminService.findUserByName(umsAdmin.getUsername());
        return ResultData.ok(adminNew, "操作成功");
    }

    // 获取指定用户信息
    public ResultData getUserInfo(Long id) {
        UmsAdmin admin = umsAdminService.getAdminById(id);
        return ResultData.ok(admin,"操作成功");
    }

    // 修改密码
    public ResultData updatePassword(AdminPasswordDto adminPasswordDto) {
        // 根据 username 查询 admin 信息
        UmsAdmin umsAdmin = umsAdminService.findUserByName(adminPasswordDto.getUsername());
        String password = umsAdmin.getPassword();
        // 与前端传来的旧密码做比较
        if (!BCryptUtil.checkPassword(adminPasswordDto.getOldPassword(), password)) {
            // 旧密码与数据库不匹配,返回错误信息
            return ResultData.error("");
        }
        // 旧密码匹配一致,将密码修改为新密码
        umsAdmin.setPassword(BCryptUtil.getPassword(adminPasswordDto.getNewPassword()));
        umsAdminService.updatePasswordByUsername(umsAdmin);
        return ResultData.ok(1, "操作成功!");
    }

//    // 刷新token
//    public Map<String, Object> refreshToken() {
//        // 根据id查询admin
//        UmsAdmin admin = umsAdminService.getAdminById(UserHolder.getUserId());
//        Map<String, Object> tokenMap = getTokenMap(admin);
//        return tokenMap;
//    }
//
//    private Map<String, Object> getTokenMap(UmsAdmin admin) {
//        // 生成token
//        Map<String, Object> tokenMap = new HashMap<>();
//        tokenMap.put("id", admin.getId());
//        tokenMap.put("username", admin.getUsername());
//        String token = JwtUtils.getToken(tokenMap);
//        // 构造返回值
//        Map<String, Object> retMap = new HashMap<>();
//        retMap.put("token", token);
//        retMap.put("tokenHead", "Bearer ");
//        return retMap;
//    }
}
